#include "weather.h"
#include "ui_weather.h"
#include <QCoreApplication>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QDate>
#include "QPainter"
weather::weather(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::weather)
{
    ui->setupUi(this);
    city_code();
    // 将表示日期的 QLabel 控件添加到 mDateList 列表中
    mDateList<<ui->labeldate1<<ui->labeldate2<<ui->labeldate3<<ui->labeldate4
              <<ui->labeldate5<<ui->labeldate6;
    // 将表示星期的 QLabel 控件添加到 mDayList 列表中
    mDayList<<ui->labelday1<<ui->labelday2<<ui->labelday3<<ui->labelday4
             <<ui->labelday5<<ui->labelday6;
    // 将表示天气的 QLabel 控件添加到 mIconList 列表中
    mIconList<<ui->labelweather1<<ui->labelweather2<<ui->labelweather3<<ui->labelweather4
              <<ui->labelweather5<<ui->labelweather6;
    // 将表示天气类型的 QLabel 控件添加到 mWeathTypeList 列表中
    mWeathTypeList<<ui->labelweathertype1<<ui->labelweathertype2<<ui->labelweathertype3
                   <<ui->labelweathertype4<<ui->labelweathertype5<<ui->labelweathertype6;
    // 将表示空气质量的 QLabel 控件添加到 mAirList 列表中
    mAirList<<ui->labelaiq1<<ui->labelaiq2<<ui->labelaiq3<<ui->labelaiq4<<ui->labelaiq5<<ui->labelaiq6;
    // 将表示风向的 QLabel 控件添加到 mFengXiangList 列表中
    mFengXiangList<<ui->labelfengday1<<ui->labelfengday2<<ui->labelfengday3
                   <<ui->labelfengday4<<ui->labelfengday5<<ui->labelfengday6;
    // 将表示风向类型的 QLabel 控件添加到 mFengXiangTypeList 列表中
    mFengXiangTypeList<<ui->labelfengdaytype1<<ui->labelfengdaytype2<<ui->labelfengdaytype3
                       <<ui->labelfengdaytype4<<ui->labelfengdaytype5<<ui->labelfengdaytype6;
    //用mTypeMap 存储了字符串键值对
    mTypeMap.insert("暴雪",":/Icon_library/baoxue.png");
    mTypeMap.insert("暴雨",":/Icon_library/baoyu.png");
    mTypeMap.insert("暴雨到大暴雨",":/Icon_library/baoyu.png");
    mTypeMap.insert("大暴雨",":/Icon_library/baoyu.png");
    mTypeMap.insert("大暴雨到特大暴雨",":/Icon_library/baoyu.png");
    mTypeMap.insert("大到暴雪",":/Icon_library/baoxue.png");
    mTypeMap.insert("大雪",":/Icon_library/baoxue.png");
    mTypeMap.insert("大雨",":/Icon_library/zhenyu.png");
    mTypeMap.insert("冻雨",":/Icon_library/zhenyu.png");
    mTypeMap.insert("多云",":/Icon_library/duoyun.png");
    mTypeMap.insert("浮尘",":/Icon_library/fuchen.png");
    mTypeMap.insert("雷阵雨",":/Icon_library/leizhenyu.png");
    mTypeMap.insert("雷阵雨伴有冰雹",":/Icon_library/leizhenyu.png");
    mTypeMap.insert("霾",":/Icon_library/wu.png");
    mTypeMap.insert("强沙尘暴",":/Icon_library/tedayangsha.png");
    mTypeMap.insert("晴",":/Icon_library/qingtian.png");
    mTypeMap.insert("沙尘暴",":/Icon_library/tedayangsha.png");
    mTypeMap.insert("特大暴雨",":/Icon_library/baoyu.png");
    mTypeMap.insert("雾",":/Icon_library/wu.png");
    mTypeMap.insert("小到中雪",":/Icon_library/zhongxue.png");
    mTypeMap.insert("小到中雨",":/Icon_library/xiaoyu.png");
    mTypeMap.insert("小雪",":/Icon_library/zhongxue.png");
    mTypeMap.insert("小雨",":/Icon_library/xiaoyu.png");
    mTypeMap.insert("雪",":/Icon_library/zhongxue.png");
    mTypeMap.insert("扬沙",":/Icon_library/yangsha.png");
    mTypeMap.insert("阴",":/Icon_library/yintian.png");
    mTypeMap.insert("雨",":/Icon_library/xiaoyu.png");
    mTypeMap.insert("雨夹雪",":/Icon_library/yujiaxue.png");
    mTypeMap.insert("阵雪",":/Icon_library/zhongxue.png");
    mTypeMap.insert("阵雨",":/Icon_library/zhenyu.png");
    mTypeMap.insert("中到大雪",":/Icon_library/baoxue.png");
    mTypeMap.insert("中到大雨",":/Icon_library/baoyu.png");
    mTypeMap.insert("中雪",":/Icon_library/zhongxue.png");
    mTypeMap.insert("中雨",":/Icon_library/zhenyu.png");

}

weather::~weather()
{
    delete ui;
}

void weather::replyFinished(QNetworkReply* reply){
    qDebug()<<"--------\"hello\"--------"<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)<<endl;
    //    QNetworkRequest::HttpStatusCodeAttribute网址返回的状态码
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200)
    {
        qDebug()<<"访问服务器成功"<<endl;
//        qDebug()<<QString(reply->readAll())<<endl;
        analysis(reply->readAll());
    }

}
void weather::analysis(QByteArray byteArray)
{
    // 清空列表
    list_low.clear();
    list_high.clear();
    list_ymd.clear();
    list_week.clear();
    list_type.clear();
    list_fengxiang.clear();
    list_fengxiangtype.clear();

    QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
    QJsonObject obj1 = doc.object();//返回文档内的对象
    if(obj1.contains("data")==false)//问文档对象是否包含data关键字
    {
        qDebug()<<"错误的data对象"<<endl;
        return;
    }
    QJsonValue data_value = obj1.value("data");//获得关键字data对应的结果
    QJsonObject objdata=data_value.toObject();//把data转化成对象
    if(objdata.contains("shidu") == false)
    {
        qDebug()<<"没有shidu对象"<<endl;
        return;
    }
    data_value = objdata.value("shidu");//得到关键字湿度的值
    shidu = data_value.toString();//得到湿度
    if(objdata.contains("pm25") == false)
    {
        qDebug()<<"没有pm25对象"<<endl;
        return;
    }
    data_value = objdata.value("pm25");//得到关键字pm25的值
    pm25 = QString::number(data_value.toInt());//得到pm25
    data_value = objdata.value("quality");//得到关键字quality的值
    quality = data_value.toString();//得到quality
    data_value = objdata.value("ganmao");//得到关键字ganmao的值
    ganmao = data_value.toString();//得到ganmao
    qDebug()<<shidu<<" "<<pm25<<" "<<quality<<" "<<ganmao<<endl;

    if(obj1.contains("cityInfo")==false)//问文档对象是否包含cityInfo关键字
    {
        qDebug()<<"错误的JSON对象"<<endl;
        return;
    }
    QJsonValue var = obj1.value("cityInfo");//获得关键字cityInfo对应的结果
    if(var.isObject() == false)
    {
        qDebug()<<"cityInfo的值不是一个对象"<<endl;
        return;
    }
    QJsonObject cityInfoObj = var.toObject();//把cityInfo的值转为一个对象
    if(cityInfoObj.contains("city") == false)
    {
        qDebug()<<"没有city对象"<<endl;
        return;
    }

    var = cityInfoObj.value("city");//得到关键字city的值
    city = var.toString();//得到城市名

    if(obj1.contains("data")==false){
        qDebug()<<"错误的data对象"<<endl;
        return;
    }
    data_value = obj1.value("data");//获得关键字data对应的结果
    QJsonObject data_object = data_value.toObject();//把data的值转为一个对象
    if(data_object.contains("forecast")==false){
        qDebug()<<"错误的forecast对象"<<endl;
        return;
    }
    QJsonValue forecast_value = data_object.value("forecast");//获得关键字forecast对应的结果
    if(forecast_value.isArray())//是否为数组？
    {
        QJsonArray forecast_array = forecast_value.toArray();//把forecast的值转为一个数组
        qDebug()<<"一共搜索到"<<forecast_array.size()<<"日天气"<<endl;
        for(int i = 0 ; i < forecast_array.size() ; i++)
        {
            QJsonObject forecast_object=forecast_array[i].toObject();
            if(forecast_object.contains("low"))
            {
                QJsonValue forecast_low = forecast_object.value("low");//获取关键字为low的元素的值
                low = forecast_low.toString();
            }
            QRegularExpression re("\\d+"); // 正则表达式，匹配一个或多个数字
            QRegularExpressionMatch match = re.match(low);
            if (match.hasMatch()) {
                low = match.captured(0); // 获取匹配到的第一个（也是唯一一个）数字字符串
//                qDebug() << "Extracted number string:" << low;
            }
            if(forecast_object.contains("high"))
            {
                QJsonValue forecast_high = forecast_object.value("high");//获取关键字为high的元素的值
                high = forecast_high.toString();
            }
            match = re.match(high);
            if (match.hasMatch()) {
                high = match.captured(0); // 获取匹配到的第一个（也是唯一一个）数字字符串
//                qDebug() << "Extracted number string:" << high;
            }
            if(forecast_object.contains("ymd"))
            {
                QJsonValue forecast_ymd = forecast_object.value("ymd");//获取关键字为ymd的元素的值
                ymd = forecast_ymd.toString();
            }
            if(forecast_object.contains("week"))
            {
                QJsonValue forecast_week = forecast_object.value("week");//获取关键字为week的元素的值
                week = forecast_week.toString();
            }
            if(forecast_object.contains("type"))
            {
                QJsonValue forecast_type = forecast_object.value("type");//获取关键字为type的元素的值
                type = forecast_type.toString();
            }
            if(forecast_object.contains("fx"))
            {
                QJsonValue forecast_fx = forecast_object.value("fx");//获取关键字为fengxiang的元素的值
                fengxiang = forecast_fx.toString();
            }
            if(forecast_object.contains("fl"))
            {
                QJsonValue forecast_fl = forecast_object.value("fl");//获取关键字为fengxiangtype的元素的值
                fengxiangtype = forecast_fl.toString();
            }
            qDebug()<<city<<" "<<low<<" "<<high<<" "<<ymd<<" "<<week<<" "<<type<<fengxiang<<" "<<fengxiangtype<<endl;

            list_low.push_back(low);
            list_high.push_back(high);
            list_ymd.push_back(ymd);
            list_week.push_back(week);
            list_type.push_back(type);
            list_fengxiang.push_back(fengxiang);
            list_fengxiangtype.push_back(fengxiangtype);



        }
        }
    updateUI();
}
void weather::city_code(){
    QFile file(":/city.txt");
       if (!file.open(QFile::ReadOnly | QFile::Text)) {
           qWarning() << "Unable to open the file.";
       }

       QTextStream in(&file);
       in.setCodec("UTF-8"); // 假设文件编码为UTF-8，如果不是，需要改为正确的编码

       while (!in.atEnd()) {
           QString line = in.readLine();
           QStringList fields = line.split("\t", QString::SkipEmptyParts);
           if (fields.size() == 2) {
               QString cityCode = fields.at(0).trimmed();
               QString cityName = fields.at(1).trimmed();
               list_code.push_back(cityCode);
               list_name.push_back((cityName));
           }
       }

}



void weather::on_pushButton_clicked()
{
    QString name=ui->lineEditCity->text();
       for (int i = 0; i < list_code.size(); ++i) {
            if(name==list_name[i]){
                code=list_code[i];
                qDebug()<<code<<endl;
            }
       }
       //创建一个网络访问管理对象
       manager = new QNetworkAccessManager(this);
       connect(manager, SIGNAL(finished(QNetworkReply*)),
               this, SLOT(replyFinished(QNetworkReply*)));
       manager->get(QNetworkRequest(QUrl(QString("http://t.weather.sojson.com/api/weather/city/")+code)));
        //安装事件过滤器，使当前对象（this）能够拦截它的事件
       ui->widget0401->installEventFilter(this);
       ui->widget0402->installEventFilter(this);
}


void weather::updateUI()
{
//解析日期
ui->labelCurrentDate->setText(list_ymd[0]+" "+list_week[0]);
//解析城市名称
ui->labelCity->setText(city);
//解析当前温度
int currentTemp=(list_low[0].toInt()+list_high[0].toInt())/2;
ui->labelTmP->setText(QString::number(currentTemp));
ui->labelTempRange->setText(list_low[0]
                            +"~"
                            +list_high[0]+"℃");
//解析天气类型
ui->labelwheatherType->setText(list_type[0]);
ui->labelWeatherIcon->setPixmap(mTypeMap.value(list_type[0]));
//感冒指数
ui->labelGanmao->setText(ganmao);
//风向
ui->labelfengxiangtype->setText(list_fengxiang[0]);
//风力
ui->labelfengxiangtype_2->setText(list_fengxiangtype[0]);
//pm2.5
ui->labelpm2_5type_2->setText(pm25);
//湿度
ui->labelshidutype_2->setText(shidu);
//空气质量
ui->labelkongqitype_2->setText(quality);
for(int i=0;i<6;i++){
    mDayList[i]->setText(list_week[i]);
    list_ymd[i].remove(0,5);
//    QDate date = QDate::fromString(list_ymd[i], "yyyy-MM-dd"); // 解析日期
//    QString formattedDateStr = QString("%1/%2").arg(date.month()).arg(date.day()); // 格式化为 "MM/dd"
//    mDateList[i]->setText(formattedDateStr);
    mDateList[i]->setText(list_ymd[i]);
    QPixmap pixmap=mTypeMap.value(list_type[i]);
//    int index=days[i].mWeatherType.indexOf("转");
//    if(index!=-1){
//        pixmap=mTypeMap[days[i].mWeatherType.left(index)];
//    }
    mIconList[i]->setPixmap(pixmap);
    mWeathTypeList[i]->setText(list_type[i]);

//    QString air=list;
//    if(air=="优")
//        mAirList[i]->setStyleSheet("background-color: rgb(65, 174, 60);border-radius: 10px;");
//    if(air=="良")
//        mAirList[i]->setStyleSheet("background-color: rgb(252, 161, 4);border-radius: 10px;");
//    if(air=="轻度污染")
//        mAirList[i]->setStyleSheet("background-color: rgb(249, 125, 28);border-radius: 10px;");
//    if(air=="中度污染")
//        mAirList[i]->setStyleSheet("background-color: rgb(238, 63, 77);border-radius: 10px;");
//    if(air=="重度污染")
//        mAirList[i]->setStyleSheet("background-color: rgb(90, 18, 22);border-radius: 10px;");
//    if(air=="严重污染")
//        mAirList[i]->setStyleSheet("background-color: rgb(166, 27, 41);border-radius: 10px;");
//    mAirList[i]->setText(days[i].mKongQiType);
    mFengXiangList[i]->setText(list_fengxiang[i]);
    mFengXiangTypeList[i]->setText(list_fengxiangtype[i]);
}
mDayList[0]->setText("今天");
mDayList[1]->setText("明天");
mDayList[2]->setText("后天");

update();
}

bool weather::eventFilter(QObject *watched, QEvent *event)
{
    if(watched==ui->widget0401&&event->type()==QEvent::Paint){
        drawTempLineHigh();
    }
    if(watched==ui->widget0402&&event->type()==QEvent::Paint){
        drawTempLineLow();
    }
    return QWidget::eventFilter(watched,event);
}

void weather::drawTempLineHigh()
{
    QColor color=QColor(254,215,26);
    QPainter painter(ui->widget0401);
    painter.setRenderHint(QPainter::Antialiasing,true);//启用了抗锯齿渲染提示，这可以让绘制出来的形状边缘更平滑
    painter.setBrush(color);
    painter.setPen(color);
    int ave;
    int sum=0;
    int offSet=0;
    int mid=ui->widget0401->height()/2;
    for(int i=0;i<6;i++){
        sum+=list_high[i].toInt();
    }
    ave=sum/6;
    //定义出6个点
    QPoint points[6];
    //遍历list_high数组，计算每个值相对于平均值的偏移量，并在ui->widget0401上绘制对应的点和温度值。
    for(int i=0;i<6;i++){
        points[i].setX(mAirList[i]->x()+mAirList[i]->width()*1.0/2);
        offSet=(list_high[i].toInt()-ave)*2;
        points[i].setY(mid-offSet);
        //画六个点
        painter.drawEllipse(QPoint(points[i]),3,3);
        //或当天温度

        painter.drawText(points[i].x()-15,points[i].y()-5,list_high[i]+"℃");
    }
    //遍历点数组，连接相邻的点
    for(int i=0;i<5;i++){
        if(i==0)
            painter.setPen(QPen(color,1,Qt::DashDotLine));
        painter.drawLine(points[i],points[i+1]);
        if(i==0)
            painter.setPen(color);
    }
    // painter.drawLine(QPoint(10,10),QPoint(30,30));
}
void weather::drawTempLineLow()
{
    QColor color=QColor(22,119,179);
    QPainter painter(ui->widget0402);
    painter.setRenderHint(QPainter::Antialiasing,true);
    painter.setBrush(color);
    painter.setPen(color);
    int ave;
    int sum=0;
    int offSet=0;
    int mid=ui->widget0402->height()/2;
    for(int i=0;i<6;i++){
        sum+=list_low[i].toInt();
    }
    ave=sum/6;
    //定义出6个点
    QPoint points[6];
    for(int i=0;i<6;i++){
        points[i].setX(mAirList[i]->x()+mAirList[i]->width()*1.0/2);
        offSet=(list_low[i].toInt()-ave)*3;
        points[i].setY(mid-offSet);
        //画六个点
        painter.drawEllipse(QPoint(points[i]),3,3);
        //或当天温度
        painter.drawText(points[i].x()-15,points[i].y()-5,list_low[i]+"℃");
    }
    for(int i=0;i<5;i++){
        if(i==0){
            painter.setPen(QPen(color,1,Qt::DashDotLine));
        }
        painter.drawLine(points[i],points[i+1]);
        if(i==0)
            painter.setPen(color);
    }
}
